<!--
 * @Author: cjy
 * @Date: 2023-04-12 11:28:19
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-04-12 17:22:05
 * @Descripttion: 
 * @FilePath: \vue-openlayers-demos\src\views\geojsonVT\GeojsonVT.vue
-->
<template>
  <div class="vm">
    <h2 class="h-title"></h2>
    <div id="map" class="map-x"></div>
  </div>
</template>
  
  <script>
//   import 'ol/ol.css'
//   import { Map, View } from 'ol'
//   import Tile from 'ol/layer/Tile'
//   import XYZ from 'ol/source/XYZ'
//   import * as control from 'ol/control'

import GeoJSON from "ol/format/GeoJSON.js";
import Map from "ol/Map.js";
import Projection from "ol/proj/Projection.js";
import VectorTileLayer from "ol/layer/VectorTile.js";
import VectorTileSource from "ol/source/VectorTile.js";
import View from "ol/View.js";
import { Fill, Style } from "ol/style.js";
import MVT from "ol/format/MVT.js";
import { createXYZ } from "ol/tilegrid";

import Tile from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import { fromLonLat } from "ol/proj";

import geojsonvt from "geojson-vt";

export default {
  name: "FirstMap",
  data() {
    return {
      map: null,
    };
  },
  methods: {
    initMap() {
      // this.map = new Map({
      //   controls: control.defaults({ zoom: false}),
      //   target: "map",
      //   layers: [
      //     new Tile({
      //       source: new XYZ({ //http://t0.tianditu.gov.cn/img_c/wmts
      //       //   url: 'http://t0.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd',
      //         url: 'http://t0.tianditu.com/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd',
      //         projection: "EPSG:4326",
      //       }),
      //     }),
      //     new Tile({
      //       source: new XYZ({
      //         url: 'http://t6.tianditu.com/DataServer?T=cva_c&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd',
      //         projection: "EPSG:4326",
      //       })
      //     })

      //   ],
      //   view: new View({
      //     // projection: "EPSG:4326",
      //     center: [110.064839, 32.548857],
      //     // minZoom:10,
      //     zoom: 5
      //   })
      // })

    //   const 

      const style = new Style({
        fill: new Fill({
          color: "#eeeeee",
        }),
      });

      const layer = new VectorTileLayer({
        style: function (feature) {
        //   const color = feature.get("COLOR") || "#eeeeee";
          const color = 'rgba(255,0,0,.3)' || "#eeeeee";
          style.getFill().setColor(color);
          return style;
        },
      });

      const map = new Map({
        layers: [
          new Tile({
            source: new XYZ({
            //   url: "http://t0.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd",
            //   projection: "EPSG:4326",
              url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd",
              projection: "EPSG:3857",
            }),
          }),
          new Tile({
            source: new XYZ({
            //   url: "http://t6.tianditu.com/DataServer?T=cva_c&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd",
            //   projection: "EPSG:4326",
              url: "http://t6.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd",
              projection: "EPSG:3857",
            }),
          }),
          new Tile({
            source: new XYZ({
                url:
                // 'http://223.4.72.162:16080/arcgis/rest/services/basemap/ZLSLVectorMap/MapServer/tile/{z}/{y}/{x}',
                'https://sldtptgis.zjwater.com/arcgis/rest/services/basemap/ZLSLVectorMap/MapServer/tile/{z}/{y}/{x}',
                // 'https://sldtpt.zjwater.com:8443/waterplatzj1/proxy.jsp?http://223.4.72.162:18099/PBS/rest/services/waterMap/MapServer/tile/{z}/{y}/{x}',
                projection: 'EPSG:4326', //使用这个坐标系
            }),
            id: 'shuili-map',
            preload: 1,
            visible: true
          }),
        ],
        target: "map",
        view: new View({
        //   projection: 'EPSG:4326',
          center: fromLonLat([119.7, 29.03]),
        //   center: [119.7, 29.03],
          zoom: 15,
        }),
      });
      
    //   const url = "https://openlayers.org/data/vector/ecoregions.json";
      const url = "https://datacenter-gcsyb.ygwjg.com/geojson/andi_gengdimianji_2022.json";
      fetch(url)
        .then( (response)  => {
          return response.json();
        })
        .then( (json) => {
          const tileIndex = geojsonvt(json, {
            maxZoom: 22,  // max zoom to preserve detail on; can't be higher than 24
            tolerance: 5, // simplification tolerance (higher means simpler)
            extent: 4096, // tile extent (both width and height)
            buffer: 64,   // tile buffer on each side
            debug: 0,     // logging level (0 to disable, 1 or 2)
            lineMetrics: false, // whether to enable line metrics tracking for LineString/MultiLineString features
            promoteId: null,    // name of a feature property to promote to feature.id. Cannot be used with `generateId`
            generateId: false,  // whether to generate feature ids. Cannot be used with `promoteId`
            indexMaxZoom: 5,       // max zoom in the initial tile index
            indexMaxPoints: 100000 // max number of points per tile in the index
          });
          const format = new GeoJSON({
            // Data returned from geojson-vt is in tile pixel units
            // dataProjection: 'EPSG:4326',
            dataProjection: new Projection({
              code: "TILE_PIXELS",
              units: "tile-pixels",
              extent: [0, 0, 4096, 4096],
            }),
            // featureProjection: 'EPSG:4326'
          });
          const vectorSource = new VectorTileSource({
            // projection: "EPSG:4326",
            tileUrlFunction:  (tileCoord) => {
              // Use the tile coordinate as a pseudo URL for caching purposes
              return JSON.stringify(tileCoord);
            },
            tileLoadFunction:  (tile, url)  =>  {
              const tileCoord = JSON.parse(url);
            //   console.log(tileCoord, "tileCoord=========================");
              const data = tileIndex.getTile(
                tileCoord[0],
                tileCoord[1],
                tileCoord[2]
              );
              const geojson = JSON.stringify(
                {
                  type: "FeatureCollection",
                  features: data ? data.features : [],
                },
                this.replacer
              );

              //   console.log(geojson, 'jjjjjjjjjjjjjjjjjjjjjjjj==========================');
              const features = format.readFeatures(geojson, {
                // dataProjection: 'EPSG:3857',
                extent: vectorSource
                  .getTileGrid()
                  .getTileCoordExtent(tileCoord),
                featureProjection: map.getView().getProjection(),
                // featureProjection: 'EPSG:4326',
                // featureProjection: 'EPSG:3857',
              });

            //   console.log(features, "features===============================");
            //   console.log(
            //     new GeoJSON().writeFeatures(features, {
            //       dataProjection: "EPSG:4326",
            //       featureProjection: "EPSG:3857",
            //     }),
            //     "=====================writeFeaturesfeatures======================"
            //   );
              //   let newwwww = (new GeoJSON()).writeFeatures(features,{
              //     dataProjection: 'EPSG:4326',
              //     featureProjection: 'EPSG:3857',
              //   })
              //   tile.setFeatures((new GeoJSON()).readFeatures(newwwww));

              tile.setFeatures(features);
            },
          });
          layer.setSource(vectorSource);
          map.addLayer(layer);
        });
    },
    replacer (key, value) {
        if (!value || !value.geometry) {
          return value;
        }

        let type;
        const rawType = value.type;
        let geometry = value.geometry;
        if (rawType === 1) {
          type = "MultiPoint";
          if (geometry.length == 1) {
            type = "Point";
            geometry = geometry[0];
          }
        } else if (rawType === 2) {
          type = "MultiLineString";
          if (geometry.length == 1) {
            type = "LineString";
            geometry = geometry[0];
          }
        } else if (rawType === 3) {
          type = "Polygon";
          if (geometry.length > 1) {
            type = "MultiPolygon";
            geometry = [geometry];
          }
        }

        return {
          type: "Feature",
          geometry: {
            type: type,
            coordinates: geometry,
          },
          properties: value.tags,
        };
    }
  },
  mounted() {
    this.initMap();
  },
  
};
</script>
  
  <style lang="scss" scoped>
</style>